// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  replaceFixedSpans();
});

// 监听页面动态变化（针对SPA应用）
const observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.addedNodes.length) {
      setTimeout(replaceFixedSpans, 100);
    }
  });
});

observer.observe(document.body, {
  childList: true,
  subtree: true
});

// 固定的替换规则
function replaceFixedSpans() {
  const replacementRules = [
    // 规则1: 按文本内容替换
    {
      type: 'text',
      target: '旧文本',
      replacement: '新文本',
      replaceAll: true
    },
    // 规则2: 按class替换
    {
      type: 'class', 
      target: 'old-price',
      replacement: '￥99.00',
      replaceAll: true
    },
    // 规则3: 按ID替换
    {
      type: 'id',
      target: 'username',
      replacement: '管理员',
      replaceAll: false
    },
    // 规则4: 自定义选择器
    {
      type: 'selector',
      target: 'span[data-role="status"]',
      replacement: '在线',
      replaceAll: true
    }
  ];

  let totalChanged = 0;

  replacementRules.forEach(rule => {
    const count = applyReplacementRule(rule);
    totalChanged += count;
  });

  if (totalChanged > 0) {
    console.log(`[Span替换器] 成功替换了 ${totalChanged} 个span元素`);
  }
}

// 应用单个替换规则
function applyReplacementRule(rule) {
  let elements = [];
  let changedCount = 0;

  try {
    switch (rule.type) {
      case 'text':
        // 查找包含特定文本的所有span
        elements = Array.from(document.querySelectorAll('span')).filter(span => 
          span.textContent.includes(rule.target)
        );
        break;
      
      case 'class':
        elements = document.querySelectorAll(`span.${rule.target}`);
        break;
      
      case 'id':
        const element = document.getElementById(rule.target);
        if (element && element.tagName.toLowerCase() === 'span') {
          elements = [element];
        }
        break;
      
      case 'selector':
        elements = document.querySelectorAll(rule.target);
        break;
    }

    if (elements.length > 0) {
      const targets = rule.replaceAll ? elements : [elements[0]];
      
      targets.forEach(element => {
        if (rule.type === 'text') {
          // 文本替换只替换匹配的部分
          element.textContent = element.textContent.replace(
            new RegExp(escapeRegExp(rule.target), 'g'), 
            rule.replacement
          );
        } else {
          // 其他类型直接替换整个内容
          element.textContent = rule.replacement;
        }
        changedCount++;
      });
    }
  } catch (error) {
    console.error(`[Span替换器] 应用规则时出错:`, error);
  }
  return changedCount;
}

// 转义正则表达式特殊字符
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}